const Koa = require('koa')
const koaStaticCache = require('koa-static-cache')
const koaRouter = require('@koa/router')
const koaBody = require('koa-body')
const nunjucks = require('nunjucks')
const fs = require('fs')


const server = new Koa()

//静态资源处理， 内部返回（ctx，next）函数
server.use(koaStaticCache({
    // url 中的前缀
    prefix: '/public',
    // url 对应的静态资源存放目录
    dir: './public',
    // 启用 gzip 传输压缩
    gzip: true,
    // 监听静态资源文件变化
    dynamic: true
}))

const items = require('./public/items.json')
//路由函数注册
const router = new koaRouter()

router.get('/',async (ctx,next)=>{
    const tpl = fs.readFileSync('./template/cart.html').toString()
    ctx.body = nunjucks.renderString(tpl,{
        items
    })
})

router.get('/detail/:id',async (ctx,next)=>{
    //  console.log(ctx.params.id)
    //  console.log(items)
    const tpl = fs.readFileSync('./template/detail.html').toString()
    const item = items.find(i=>i.id == ctx.params.id)
    // console.log(item)
    ctx.body = nunjucks.renderString(tpl,item)
})

router.post('/add-common',koaBody(),(ctx,next)=>{
console.log(ctx.request.body)
})

server.use(router.routes())

//实现 const server = http.createServer(this.callback());
//return server.listen(...args);
server.listen(8000)